package com.hmall.item.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;

import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("list")
    public PageDTO list(@RequestParam(value = "page") Integer page,
                         @RequestParam(value = "size") Integer size){
        log.info("当前页面：{}，分页大小：{}", page, size);

        /*IPage page1 = new Page(page,size);
        itemService.page(page1,null);
        PageDTO pageDTO = new PageDTO();
        pageDTO.setTotal(page1.getTotal());
        pageDTO.setList(page1.getRecords());*/

        Page<Item> result = itemService.page(new Page<>(page, size));
        return new PageDTO(result.getTotal(), result.getRecords());
    }

    /**
     * 根据id查询商品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id){
        log.info("查询id为：{}",id);
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 新增
     * @param item
     */
    @PostMapping
    public void add(@RequestBody Item item){
        log.info("新增的参数为：{}",item);
        itemService.save(item);
    }

    /**
     * 商品上下架
     * @param id
     * @param status
     */
    @PutMapping("status/{id}/{status}")
    public void status(@PathVariable Long id,@PathVariable Integer status){
        log.info("修改id为：{}，的商品状态为：{}",id,status);
        Item item = itemService.getById(id);
        item.setStatus(status);
        itemService.updateById(item);
    }

    /**
     * 修改
     * @param item
     */
    @PutMapping
    public void update(@RequestBody Item item){
        log.info("修改的数据为：{}",item);
        itemService.updateById(item);
    }

    @DeleteMapping("{id}")
    public void delete(@PathVariable Long id){
        log.info("需要删除的id值为：",id);
        itemService.removeById(id);
    }
}
